package com.pig4cloud.pig.module.controller.mer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.mer.MerSelfVip;
import com.pig4cloud.pig.module.api.entity.mer.MerSelfVipRechargeRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.mer.IMerSelfVipRechargeRecordService;
import com.pig4cloud.pig.module.service.mer.IMerSelfVipService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 商家的自有会员Controller
 *
 * @author ruoyi
 * @date 2023-05-28
 */
@Validated
@Api(value = "商家的自有会员控制器", tags = {"商家的自有会员管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/mer/self/vip")
public class MerSelfVipController {

    private final IMerSelfVipService merSelfVipService;
    private final IMerSelfVipRechargeRecordService vipRechargeRecordService;
	private final IWxUserService wxUserService;

    @Value("${ruoyi.profile}")
    private String uploadPath;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询商家的自有会员列表
     */
    @ApiOperation("查询商家的自有会员列表")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:list')")
    @GetMapping("/list")
    public TableDataInfo<MerSelfVip> list(@Validated MerSelfVip merSelfVip) {
        QueryWrapper<MerSelfVip> qw = new QueryWrapper<>();
        if(merSelfVip.getCardNum()!=null){
            qw.eq("card_num",merSelfVip.getCardNum());
        }
		if(merSelfVip.getMerId()!= null){
			qw.eq("mer_id",merSelfVip.getMerId());
		}
        if(StrUtil.isNotEmpty(merSelfVip.getRealName())){
            qw.like("real_name",merSelfVip.getRealName())
                    .or().like("phone_num",merSelfVip.getRealName())
                    .or().like("car_num",merSelfVip.getRealName());
        }
		qw.orderByDesc("id");

        TableDataInfo<MerSelfVip> td = PageUtils.buildDataInfo(merSelfVipService.page(PageUtils.buildPage(),qw));
        List<MerSelfVip> list = td.getData();
		if(CollUtil.isNotEmpty(list)){
			for (MerSelfVip selfVip : list){
				WxUser wxUser = wxUserService.findById(selfVip.getWxUserId());
				if(wxUser!= null){
					selfVip.setNickName(wxUser.getNickName());
				}
				if(StrUtil.isNotEmpty(selfVip.getQrCode())){
					selfVip.setQrCode(imgUrl + selfVip.getQrCode());
				}
			}
		}
        return td;
    }


    /**
     * 查询商家的自有会员余额
     */
    @ApiOperation("查询商家的自有会员列表")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:list')")
    @GetMapping("/list/money")
    public Double vipMoney(@Validated MerSelfVip merSelfVip){
        Double money = 0.00;
        MerSelfVip merSelfVip1 = merSelfVipService.selectByUniqueColumn("card_num", merSelfVip.getCardNum());
        if (merSelfVip1!=null){
            if (merSelfVip1.getAccountMoney()!=null){
                money=merSelfVip1.getAccountMoney().doubleValue();
            }
        }
        return money;
    }
    /**
     * 导出商家的自有会员列表
     */
    @ApiOperation("导出商家的自有会员列表")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:export')")
    @SysLog("商家的自有会员")
    @GetMapping("/export")
    public List export(@Validated MerSelfVip merSelfVip) {
        List<MerSelfVip> list = merSelfVipService.list();
        // ExcelUtil<MerSelfVip> util = new // ExcelUtil<MerSelfVip>(MerSelfVip.class);
        return  list;// util.exportExcel(list, "商家的自有会员");
    }

    /**
     * 获取商家的自有会员详细信息
     */
    @ApiOperation("获取商家的自有会员详细信息")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:query')")
    @GetMapping("/{id}")
    public R<MerSelfVip> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        MerSelfVip merSelfVip = merSelfVipService.getById(id);
        return R.ok(merSelfVip);
    }

    /**
     * 新增商家的自有会员
     */
    @ApiOperation("新增商家的自有会员")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:add')")
    @SysLog("商家的自有会员")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody MerSelfVip merSelfVip) {
        PigUser sysUser = SecurityUtils.getUser();
        merSelfVip.setRechargeTotalMoney(merSelfVip.getAccountMoney());
		boolean bl = merSelfVipService.save(merSelfVip);
		if(bl){

		    if(merSelfVip.getAccountMoney() != null && merSelfVip.getAccountMoney().doubleValue() > 0){
                MerSelfVipRechargeRecord rechargeRecord = new MerSelfVipRechargeRecord();
                rechargeRecord.setMerId(merSelfVip.getMerId());
                rechargeRecord.setSelfVipId(merSelfVip.getId());
                rechargeRecord.setBeforeMoney(new BigDecimal(0));
                rechargeRecord.setRechargeMoney(merSelfVip.getAccountMoney());
                rechargeRecord.setVipName(merSelfVip.getRealName());
                rechargeRecord.setVipPhone(merSelfVip.getPhoneNum());
                rechargeRecord.setRechargeType(0);
                rechargeRecord.setOpSysUserId(sysUser.getId());
                rechargeRecord.setOpSysUserName(sysUser.getName());
                rechargeRecord.setCreateTime(new Date());
                rechargeRecord.setRemark("开会员时预充值费用");
                vipRechargeRecordService.save(rechargeRecord);
            }

			String cardNum = String.format("%06d",merSelfVip.getMerId()) + String.format("%06d",merSelfVip.getId());
			merSelfVip.setCardNum(cardNum);

			try{
				String qrCode = "";
				String fileName = "";
				String content = "";
				fileName = "mer_vip_" + merSelfVip.getId() + ".jpg";
				content = "https://www.sdyuedou.com/wxmini/merVip/info?id=" + merSelfVip.getId();
				int upload_type = 0;// FileUploadUtils.TYPE_MER_VIP;
				System.out.println("content:  "+ content);
				String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, "NO. " +merSelfVip.getCardNum(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				qrCode = img_key;
				merSelfVip.setQrCode(qrCode);

			}catch (Exception ex){
				ex.printStackTrace();
			}

			bl = merSelfVipService.updateById(merSelfVip);
		}
        return R.okByRow(bl ? 1 : 0);
    }


    /**
     * 新增不记名会员卡
     */
    @ApiOperation("新增商家的自有会员")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:add')")
    @SysLog("商家的自有会员")

    @PostMapping("/un")
    public R<Void> addUn(@Valid @RequestBody MerSelfVip merSelfVip) {
        MerSelfVip merSelfVip1 = merSelfVipService.selectByUniqueColumn("card_num",merSelfVip.getCardNum());
        if (merSelfVip1!=null){
            return R.okByRow(false);
        }
        PigUser sysUser = SecurityUtils.getUser();
        merSelfVip.setRechargeTotalMoney(merSelfVip.getAccountMoney());
        merSelfVip.setRealName("不记名会员");
        merSelfVip.setPhoneNum("0");
        Date date = new Date();
        merSelfVip.setBirthday(date);
        merSelfVip.setWxUserId(32119);

        boolean bl = merSelfVipService.save(merSelfVip);
        if(bl){

            if(merSelfVip.getAccountMoney() != null && merSelfVip.getAccountMoney().doubleValue() > 0){
                MerSelfVipRechargeRecord rechargeRecord = new MerSelfVipRechargeRecord();
                rechargeRecord.setMerId(merSelfVip.getMerId());
                rechargeRecord.setSelfVipId(merSelfVip.getId());
                rechargeRecord.setBeforeMoney(new BigDecimal(0));
                rechargeRecord.setRechargeMoney(merSelfVip.getAccountMoney());
                rechargeRecord.setVipName(merSelfVip.getRealName());
                rechargeRecord.setVipPhone(merSelfVip.getPhoneNum());
                rechargeRecord.setRechargeType(0);
                rechargeRecord.setOpSysUserId(sysUser.getId());
                rechargeRecord.setOpSysUserName(sysUser.getName());
                rechargeRecord.setCreateTime(new Date());
                rechargeRecord.setRemark("开会员时预充值费用");
                vipRechargeRecordService.save(rechargeRecord);
            }

            try{
                String qrCode = "";
                String fileName = "";
                String content = "";
                fileName = "mer_vip_" + merSelfVip.getId() + ".jpg";
                content = "https://www.sdyuedou.com/wxmini/merVip/info?id=" + merSelfVip.getId();
                int upload_type = 0;//FileUploadUtils.TYPE_MER_VIP;
                System.out.println("content:  "+ content);
                String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, "NO. " +merSelfVip.getCardNum(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                qrCode = img_key;
                merSelfVip.setQrCode(qrCode);

            }catch (Exception ex){
                ex.printStackTrace();
            }

            bl = merSelfVipService.updateById(merSelfVip);
        }
        return R.okByRow(bl ? 1 : 0);
    }
    /**
     * 修改商家的自有会员
     */
    @ApiOperation("修改商家的自有会员")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:edit')")
    @SysLog("商家的自有会员")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody MerSelfVip merSelfVip) {
		if(StrUtil.isEmpty(merSelfVip.getCardNum())){
			String cardNum =  String.format("%06d",merSelfVip.getMerId()) +String.format("%06d",merSelfVip.getId());
			merSelfVip.setCardNum(cardNum);
		}
        return R.okByRow(merSelfVipService.updateById(merSelfVip) ? 1 : 0);
    }


    /**
     * 充值
     */
    @ApiOperation("充值")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:edit')")
    @SysLog("充值")

    @PutMapping("/recharge")
    public R<Void> recharge(@Valid @RequestBody MerSelfVip merSelfVip) {
        PigUser sysUser = SecurityUtils.getUser();
        int ret = merSelfVipService.recharge(merSelfVip, sysUser);
        return R.okByRow(ret);
    }

    /**
     * 删除商家的自有会员
     */
    @ApiOperation("删除商家的自有会员")
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:remove')")
    @SysLog("商家的自有会员")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(merSelfVipService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    @SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:merSelfVip:edit')")
    public R<Void> resetQrCode(@RequestBody MerSelfVip merSelfVip) {
        if(merSelfVip.getId()!=null){
            merSelfVip = merSelfVipService.findById(merSelfVip.getId());
			try{
				String qrCode = "";
				String fileName = "mer_vip_" + merSelfVip.getId() + ".jpg";
				String content = "https://www.sdyuedou.com/wxmini/merVip/info?id=" + merSelfVip.getId();
				int upload_type = 0;//FileUploadUtils.TYPE_MER_VIP;
				System.out.println("content:  "+ content);
				String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, "NO. " + merSelfVip.getCardNum(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				qrCode = img_key;
				merSelfVip.setQrCode(qrCode);

			}catch (Exception ex){
				ex.printStackTrace();
			}
            if (merSelfVipService.updateById(merSelfVip)) {
                return R.ok();
            }
        }
        return R.failed();
    }
}
